import java.io.Console;
import java.io.IOException;
import java.lang.reflect.*;

public class TermOwareGame {
	public MancalaPlayer player[];
	public MancalaGameState gs;

	// Using reflection to instantiate player classes from command line
	public TermOwareGame(MancalaGameState gs, String player0Name,
			String player1Name) {
		this.gs = gs;
		player = new MancalaPlayer[2];
		try {
			Class<?> cls = Class.forName(player0Name + "_Player");
			Class partypes[] = new Class[1];
			partypes[0] = int.class;
			Constructor ct = cls.getConstructor(partypes);
			Object arglist[] = new Object[1];
			arglist[0] = new Integer(0);
			player[0] = (MancalaPlayer) ct.newInstance(arglist);
		} catch (Throwable e) {
			System.err.println(e);
		}
		try {
			Class<?> cls = Class.forName(player1Name + "_Player");
			Class partypes[] = new Class[1];
			partypes[0] = int.class;
			Constructor ct = cls.getConstructor(partypes);
			Object arglist[] = new Object[1];
			arglist[0] = new Integer(1);
			player[1] = (MancalaPlayer) ct.newInstance(arglist);
		} catch (Throwable e) {
			System.err.println(e);
		}
	}

	public void play() throws Exception {
		while (!gs.checkEndGame()) {
			gs.printState();
			System.out.println("Player " + gs.CurrentPlayer() + "'s move: ");
			int move = player[gs.CurrentPlayer()].getMove(gs);
			while (!gs.validMove(move)) {
				System.out.println("Invalid move!");
				System.out
				.println("Player " + gs.CurrentPlayer() + "'s move: ");
				move = player[gs.CurrentPlayer()].getMove(gs);
			}
			gs.play(move);
		}
		gs.printState();

		gs.computeFinalScore();
		System.out.println("After moving in remaining pieces: ");
		gs.printState();

		System.out.println("Player 0 score: " + gs.getScore(0));
		System.out.println("Player 1 score: " + gs.getScore(1));
	}

	public static void main(String[] args) throws Exception {

		MancalaGameState gs = new OwareGameState(4);
		String[] players = new String[2];
		if (args.length > 0)
			players[0] = args[0];
		else
			players[0] = "interactive";
		if (args.length > 1)
			players[1] = args[1];
		else
			players[1] = "random";

		TermOwareGame game = new TermOwareGame(gs, players[0], players[1]);
		game.play();
	}
}
